package topic;

import com.rabbitmq.client.*;
import constant.Constant;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer2 {
    public static void main(String[] args) throws IOException, InterruptedException, TimeoutException {
        //1.创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constant.Host);
        connectionFactory.setPort(Constant.Port);
        connectionFactory.setUsername(Constant.userName);
        connectionFactory.setPassword(Constant.password);
        connectionFactory.setVirtualHost(Constant.VirtualHost);
        Connection connection = connectionFactory.newConnection();
        //2.创建channel
        Channel channel = connection.createChannel();
        //3.声明队列(可以省略,但是不建议,生产者已经启动,并生产了,就可以省略)
        // 如果队列不存在就直接创建,存在就不创建
        channel.queueDeclare(Constant.TOPIC_QUEUE2,true,false,false,null);
        //4.消费消息
        /**
         * 参数:
         * queue: 消费的队列名
         * autoAck: 自动确认
         * callback: 接收到消息之后执行的逻辑
         */
        DefaultConsumer consumer = new DefaultConsumer(channel){
            // 实现consumer接口

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //定义如何处理消息,从队列中收到消息就会执行的方法
                System.out.println("接收到消息: "+new String(body));
            }
        };
        channel.basicConsume(Constant.TOPIC_QUEUE2,true,consumer);
        //5.释放资源

        Thread.sleep(2000);

        channel.close();
        connection.close();
    }
}
